#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#       
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#       
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.

import gtk
import appindicator
import os
import time
import threading
import commands
import sys

lang = 'RU' 

def kill_me():
    global pid
    os.system('kill -9 %s' % (str(pid)))
    sys.exit(0)

def _(text):
    """Will be replaced by gettext if needed"""
    if lang == 'RU':
        if text == 'Play':
            return u'Воспроизвести'
        elif text == 'Pause':
            return u'Приостановить'
        elif text == 'Show':
            return u'Показать'
        elif text == 'Next':
            return u'Следующая'
        elif text == 'Previos':
            return u'Предыдущая'
        elif text == 'Exit':
            return u'Выйти'
        elif text == "No song playing now":
            return u'Ничего не воспроизводится'
    else:
        return text
    

class interface(threading.Thread):
    
    def __init__(self):
        threading.Thread.__init__(self)
    
    def create(self, buf, func = None):
        """Create menu object"""
        item = gtk.MenuItem(buf)
        if func != None:
            item.connect("activate", func, buf)
        self.menu.append(item)
        item.show()
        return(item)
    
    def show(self, widget, string):
        """Show deadbeef"""
        os.system('deadbeef')
            
    def play(self, widget, string):
        """Play or pause"""
        needle = commands.getoutput('deadbeef --nowplaying "%a - %t"')
        needle = needle.splitlines()
        if 'nothing' in needle:
            os.system('deadbeef --play')
        else:
            os.system('deadbeef --pause')

    def after(self, widget, string):
        """Next song"""
        os.system('deadbeef --next')

    def previos(self, widget, string):
        """Previos song"""
        os.system('deadbeef --prev')
        
    def kill_me(self, widget, string):
        """Close deadbeef"""
        os.system('deadbeef --quit')
        kill_me()
        
    def set_play(self):
        """Set play title"""
        self.play_menu.set_label(_('Play'))
        
    def set_pause(self):
        """Set pause title"""
        self.play_menu.set_label(_('Pause'))
        
    def set_no_song(self):
        """Set no song play now"""
        self.now.set_label(_("No song playing now"))
        
    def set_song(self, song):
        """Set song title"""
        self.now.set_label(song)
    
    def run(self):
        self.ind = appindicator.Indicator ("deadindicator", 
        "deadindicator", appindicator.CATEGORY_APPLICATION_STATUS)
        self.ind.set_icon('deadbeef_passive')
        self.ind.set_attention_icon ("deadbeef_active")
        self.ind.set_status (appindicator.STATUS_ACTIVE)
        self.menu = gtk.Menu()
        self.now = self.create(_("No song playing now"))
        self.show = self.create(_("Show"), self.show)
        self.play_menu = self.create(_("Play"), self.play)
        self.next_menu = self.create(_("Next"), self.after)
        self.previos_menu = self.create(_("Previos"), self.previos)
        self.getout = self.create(_("Exit"), self.kill_me)
        self.ind.set_menu(self.menu)
        gtk.main()
    
class nowplaying(threading.Thread):
    
    def __init__(self):
        threading.Thread.__init__(self)
   
    def kill_me(self):
        kill_me()
        
    def run(self):
        while True:
            not_runned = commands.getoutput('ps -e | grep deadbeef || echo 1')

            if not_runned == '1':
                print 'byby'
                self.kill_me()
                
            needle = commands.getoutput('deadbeef --nowplaying "%a - %t||||%e"').splitlines()
            if 'nothing' not in needle:
                try:
                    (nowplaying, elapsed) = needle[1].split('||||')
                    int.set_song(nowplaying)
                    time.sleep(1)
                    needle = commands.getoutput('deadbeef --nowplaying "%e"').splitlines()
                    if needle[1] != elapsed:
                        int.ind.set_status(appindicator.STATUS_ATTENTION)
                        int.set_pause()
                    else:
                        int.ind.set_status(appindicator.STATUS_ACTIVE)
                        int.set_play()
                except:
                    int.ind.set_status(appindicator.STATUS_ACTIVE)
                    int.set_play()
                    int.set_no_song()
            else:
                int.ind.set_status(appindicator.STATUS_ACTIVE)
                int.set_play()
                int.set_no_song()
            time.sleep(0.1)


if __name__ == "__main__":
    #automatic add need option to config
    config_path = '$HOME/.config/deadbeef/config'
    close_to_tray = 'close_send_to_tray 1'
    os.system('cat "%s"|grep "%s"||echo "%s">>"%s"' % 
        (config_path, close_to_tray, close_to_tray, config_path))
    #check for argv to preventing erase of playlist
    if sys.argv[1:]:
        os.system('deadbeef "%s" &' % ('"  "'.join(sys.argv[1:])))
    else:
        os.system('deadbeef &') 
    runned = commands.getoutput('ps -e|grep deadindicator|wc -l')
    if runned != '1':
       sys.exit()
    pid = os.getpid()
    gtk.gdk.threads_init()
    gtk.gdk.threads_enter()
    int = interface()
    int.start()
    gtk.gdk.threads_leave()
    now = nowplaying()
    now.start()
    
